const path = require("path");
//自动生成html代码
const HtmlWebpackPlugin = require("html-webpack-plugin");

//打包css代码
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
  //mode: "development",
  entry: {
    login: path.resolve(__dirname, "src/login/login.js"),
    content: path.resolve(__dirname, "src/content/index.js"),
  },
  devtool: "inline-source-map",
  devServer: {
    static: "./dist",
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "./[name]/[name].js",
    clean: true, //生成打包后内容前清空dist目录
  },
  //插件
  plugins: [
    //自动输出html文件
    new HtmlWebpackPlugin({
      title: "development",
      template: path.resolve(__dirname, "public/login.html"), //模板文件
      filename: path.resolve(__dirname, "dist/login/login.html"), //输出文件
      chunks: ["login"],
    }),
    new HtmlWebpackPlugin({
      title: "development",
      template: path.resolve(__dirname, "public/content.html"), //模板文件
      filename: path.resolve(__dirname, "dist/content/content.html"), //输出文件
      chunks: ["content"],
    }),
    //将css代码打包生成单独的css文件
    new MiniCssExtractPlugin({
      filename: "./[name]/[name].css",
    }),
  ],
  // 加载器从后向前执行
  module: {
    rules: [
      {
        test: /\.css$/i, //i 表示不区分大小写
        //use: ["style-loader", "css-loader"], // 将css代码打包到js文件中
        //use: [MiniCssExtractPlugin.loader, "css-loader"], //将css代码生成单独的css文件
        use: [MiniCssExtractPlugin.loader, "css-loader"], //压缩css代码
      },
      //打包less代码
      {
        test: /\.less$/i,
        use: [
          // compiles Less to CSS
          MiniCssExtractPlugin.loader, //或 "style-loader",
          "css-loader",
          "less-loader",
        ],
      },
      //打包图片代码
      {
        test: /\.(png|jpg|gif)$/i,
        type: "asset",
        generator: {
          filename: "static/[hash][ext][query]",
        },
      },
    ],
  },
  //优化打包过程
  optimization: {
    //最小化文件配置
    minimizer: [
      // 在 webpack@5 中，你可以使用 `...` 语法来扩展现有的 minimizer（即 `terser-webpack-plugin`），将下一行取消注释
      `...`,
      new CssMinimizerPlugin(),
    ],
    //分割公共代码
    splitChunks: {
      chunks: "all", //所有模块动态非动态移入的都分割分析
      //分割组
      cacheGroups: {
        //抽取公共模块
        commons: {
          //minSize: 0, //抽取的chuck最小字节
          //minChucks: 2, //最小引用数
          //reuseExistingChuck: true, //当前chuck包含已从主bundle中拆分出的模块，则将被重用
          //test: /[\\/]node_modules[\\/]/, //只分割nodemodules中的包
          //分离出模块文件名
          name(module, chunks, cacheGroupKey) {
            //分离出模块文件名
            // const moduleFileName = module
            //   .identifier()
            //   .split("/")
            //   .reduceRight((item) => item);
            const allChunksNames = chunks.map((item) => item.name).join("~");
            return `./js/${allChunksNames}`;
          },
        },
      },
    },
  },
};
